import React, { useState, useEffect, useLayoutEffect } from 'react'
import styles from './index.module.scss'
import {
  getHouseInfo,
  getIsFavorite,
  addFavorites,
  deleteFavorites
} from '@/api/detail'
import MyNavBar from '@/components/MyNavBar'
import { Carousel, Flex, Modal, Toast } from 'antd-mobile'
import classNames from 'classnames'
import HouseItem from '@/components/HouseItem'
import HouseMatch from '@/components/HouseMatch'
import { getToken } from '@/utils/token'

const labelStyle = {
  position: 'absolute',
  zIndex: -1,
  backgroundColor: 'rgb(238, 93, 91)',
  color: 'rgb(255, 255, 255)',
  height: 25,
  padding: '5px 10px',
  lineHeight: '14px',
  borderRadius: 3,
  boxShadow: 'rgb(204, 204, 204) 2px 2px 2px',
  whiteSpace: 'nowrap',
  fontSize: 12,
  userSelect: 'none'
}

const BMap = window.BMap

// 猜你喜欢
const recommendHouses = [
  {
    id: 1,
    houseCode: '5cc477061439630e5b467b0b',
    houseImg: '/newImg/7bk83o0cf.jpg',
    desc: '72.32㎡/南 北/低楼层',
    title: '安贞西里 3室1厅',
    price: 4500,
    tags: ['随时看房']
  },
  {
    id: 2,
    houseCode: '5cc4a1dd1439630e5b502266',
    houseImg: '/newImg/7bk83o0cf.jpg',
    desc: '83㎡/南/高楼层',
    title: '天居园 2室1厅',
    price: 7200,
    tags: ['近地铁']
  },
  {
    id: 3,
    houseCode: '5cc46a921439630e5b439611',
    houseImg: '/newImg/7bk83o0cf.jpg',
    desc: '52㎡/西南/低楼层',
    title: '角门甲4号院 1室1厅',
    price: 4300,
    tags: ['集中供暖']
  }
]

function Detail ({
  history,
  match: {
    params: { id }
  }
}) {
  // houseInfo数据
  const [houseInfo, setHouseInfo] = useState(null)
  // 轮播图图片高度
  const [imgHeight, setImgHeight] = useState(252)
  // 是否收藏
  const [isFavorite, setIsFavorite] = useState(false)

  const getHouseInfoData = async () => {
    const res = await getHouseInfo(id)

    setHouseInfo(res.data.body)
  }

  const getIsFavoriteData = async () => {
    const res = await getIsFavorite(id)

    if (res.data.status === 200) {
      setIsFavorite(res.data.body.isFavorite)
    }
  }

  useEffect(() => {
    getHouseInfoData()
    getIsFavoriteData()
  }, [])

  useLayoutEffect(() => {
    initMap()
  }, [houseInfo])

  // 渲染轮播图
  const renderSwiper = () => {
    return (
      <Carousel className={styles.slides} autoplay infinite>
        {houseInfo.houseImg.map(item => (
          <a
            key={item}
            href='http://www.alipay.com'
            style={{
              display: 'inline-block',
              width: '100%',
              height: imgHeight
            }}
          >
            <img
              src={`${process.env.REACT_APP_BASEURL}${item}`}
              alt=''
              style={{ width: '100%', height: '100%', verticalAlign: 'top' }}
              onLoad={() => {
                // fire window resize event to change height
                window.dispatchEvent(new Event('resize'))
                setImgHeight(252)
              }}
            />
          </a>
        ))}
      </Carousel>
    )
  }

  /**
   * 渲染基本信息
   */
  const renderBaseInfo = () => {
    return (
      <div className={styles.info}>
        <h3 className={styles.infoTitle}>{houseInfo.title}</h3>
        <Flex className={styles.tags}>
          {houseInfo.tags.map((item, index) => {
            const tagName = `tag${(index % 3) + 1}`
            return (
              <span
                className={classNames(styles.tag, styles[tagName])}
                key={item}
              >
                {item}
              </span>
            )
          })}
        </Flex>
        <Flex className={styles.infoPrice} align='center'>
          <Flex.Item className={styles.infoPriceItem}>
            <div>
              {houseInfo.price}
              <span className={styles.month}>/月</span>
            </div>
            <div>租金</div>
          </Flex.Item>
          <Flex.Item className={styles.infoPriceItem}>
            <div>{houseInfo.roomType}</div>
            <div>房型</div>
          </Flex.Item>
          <Flex.Item className={styles.infoPriceItem}>
            <div>{houseInfo.size}</div>
            <div>面积</div>
          </Flex.Item>
        </Flex>
        <Flex className={styles.infoBasic} align='center'>
          <Flex.Item>
            <div>
              <span className={styles.title}>装修：</span>
              精装修
            </div>
            <div>
              <span className={styles.title}>楼层：</span>
              {houseInfo.floor}
            </div>
          </Flex.Item>
          <Flex.Item>
            <div>
              <span className={styles.title}>朝向：</span>
              {houseInfo.oriented && houseInfo.oriented.join(' ')}
            </div>
            <div>
              <span className={styles.title}>类型：</span>普通住宅
            </div>
          </Flex.Item>
        </Flex>
      </div>
    )
  }

  // 初始化地图及覆盖物
  const initMap = () => {
    if (!houseInfo) return

    const {
      coord: { longitude, latitude },
      community
    } = houseInfo

    // 创建地图实例
    const map = new BMap.Map('map')

    // 设置中心点或是经纬度
    var point = new BMap.Point(longitude, latitude)
    map.centerAndZoom(point, 15)

    // 覆盖物
    var opts = {
      position: point, // 指定文本标注所在的地理位置
      offset: new BMap.Size(-36, -66) //设置文本偏移量
    }
    var label = new BMap.Label('', opts) // 创建文本标注对象
    label.setStyle(labelStyle)
    label.setContent(`
      <div>${community}</div>
      <div class=${styles.mapArrow}></div>
    `)
    map.addOverlay(label)
  }

  /**
   * 渲染小区地图
   */
  const renderMap = () => {
    const { community } = houseInfo

    return (
      <div className={styles.map}>
        <div className={styles.mapTitle}>
          小区：<span>{community}</span>
        </div>
        <div className={styles.mapContainer} id='map'></div>
      </div>
    )
  }

  // 渲染房屋配套
  const renderHouseMatch = () => {
    const { supporting } = houseInfo
    return (
      <div className={styles.about}>
        <div className={styles.houseTitle}>房屋配套</div>
        <div>
          {supporting.length > 0 ? (
            <HouseMatch data={supporting} />
          ) : (
            '暂无数据'
          )}
        </div>
      </div>
    )
  }

  // 渲染房屋描述
  const renderDescription = () => {
    return (
      <div className={styles.set}>
        <div className={styles.houseTitle}></div>
        <div>
          <div className={styles.contact}>
            <div className={styles.user}>
              <img src='http://huangjiangjun.top:8088/img/avatar.png' alt='' />
              <div className={styles.useInfo}>
                <div>王女士</div>
                <div className={styles.userAuth}>
                  <i className='iconfont icon-auth'></i>
                  已认证房主
                </div>
              </div>
            </div>
            <div className={styles.userMsg}>发消息</div>
          </div>
        </div>
        <div className={styles.descText}>
          {houseInfo.description.length > 0
            ? houseInfo.description
            : '暂无描述'}
        </div>
      </div>
    )
  }

  /**
   * 渲染推荐的房源
   */
  const renderRecommend = () => {
    return (
      <div className={styles.recommend}>
        <div className={styles.houseTitle}>猜你喜欢</div>
        <div className={styles.items}>
          {recommendHouses.map(item => {
            return <HouseItem key={item.houseCode} {...item} />
          })}
        </div>
      </div>
    )
  }

  /**
   * 收藏或取消收藏
   */
  const favoriteOrNot = async () => {
    // 判断一下是否登录，如果没有登录，则提示，让其登录
    const token = getToken()

    if (!token) {
      Modal.alert('提示', '登录后才能收藏房源，是否去登录?', [
        { text: '取消', onPress: () => console.log('cancel') },
        {
          text: '去登录',
          onPress: () => history.push('/login')
        }
      ])

      return
    }

    if (isFavorite) {
      // 之前收藏过，现在要取消收藏
      const res = await deleteFavorites(id)

      if (res.data.status === 200) {
        Toast.info(res.data.description, 1.5)

        setIsFavorite(false)
      }
    } else {
      // 之前没有收藏过，现在要收藏
      const res = await addFavorites(id)

      if (res.data.status === 200) {
        Toast.info(res.data.description, 1.5)

        setIsFavorite(true)
      }
    }
  }

  /**
   * 渲染底部
   */
  const renderFooter = () => {
    return (
      <Flex className={styles.fixedBottom} align='center'>
        <Flex.Item onClick={() => favoriteOrNot()}>
          <img
            style={{ height: 16 }}
            className={styles.favoriteImg}
            src={
              isFavorite
                ? 'http://huangjiangjun.top:8088/img/star.png'
                : 'http://huangjiangjun.top:8088/img/unstar.png'
            }
          />
          <span className={styles.favorite}>
            {isFavorite ? '已收藏' : '收藏'}
          </span>
        </Flex.Item>
        <Flex.Item>在线咨询</Flex.Item>
        <Flex.Item className={styles.telephone}>
          <a className={styles.telephone} href='tel:4001234567'>
            电话预约
          </a>
        </Flex.Item>
      </Flex>
    )
  }

  return (
    <div className={styles.root}>
      <MyNavBar
        className={styles.detailHeader}
        rightContent={[<i key='right' className='iconfont icon-share' />]}
      >
        {houseInfo != null ? houseInfo.community : '加载中...'}
      </MyNavBar>
      {houseInfo && renderSwiper()}
      {houseInfo && renderBaseInfo()}
      {houseInfo && renderMap()}
      {houseInfo && renderHouseMatch()}
      {houseInfo && renderDescription()}
      {houseInfo && renderRecommend()}
      {houseInfo && renderFooter()}
    </div>
  )
}

export default Detail
